#include <stdio.h>
#include <math.h>

float fungsix(float x){
	float hasil = x * exp(-x) + 1;
	return hasil;
}

void main(){
	int iterasi;
	float xbawah, xatas, x, toleran, fa, fb, fx;
	printf("Masukkan batas bawah\t\t: ");
	scanf("%f", &xbawah);
	printf("Masukkan batas atas\t\t: ");
	scanf("%f", &xatas);
	printf("Masukkan nilai toleransi\t: ");
	scanf("%f", &toleran);
	printf("Masukkan banyaknya iterasi\t: ");
	scanf("%d", &iterasi);
	printf("\n");

	if(fungsix(xbawah) * fungsix(xatas) > 0){
		printf("Tidak adak akar.\n");
	}else{

		printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
		printf("|Iterasi|    a    |    b    |    x    |   f(a)  |   f(b)  |   f(x)  |  Ket  |\n");
		printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
		for(int i=0; i<iterasi;i++){
			
			x = (xatas + xbawah)/2;
			fa = fungsix(xbawah);
			fb = fungsix(xatas);
			fx = fungsix(x);

			printf("|%7.d", i+1);
			printf("| %+.5f", xbawah);
			printf("| %+.5f", xatas);
			printf("| %+.5f", x);
			printf("| %+.5f", fa);
			printf("| %+.5f", fb);
			printf("| %+.5f", fx);
			if(fx * fa < 0){
				xatas = x;
				printf("| Lawan ");
			}else{
				xbawah = x;
				printf("|       ");
			}
			printf("|\n");
			if(abs(xatas - xbawah) < toleran){
				break;
			}
		}
		printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n");
		printf("Titik Penyelesaian\t: %.5f\n", x);
		printf("f(x)\t\t\t: %.5f\n\n", fx);
	}

}